package echat.future.cn.echat.home

import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.support.v4.view.ViewPager
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import com.bumptech.glide.Glide
import com.dotlibrary.BezierBannerDot
import com.zhusx.core.adapter._BasePagerAdapter
import com.zhusx.core.adapter._HFRecyclerAdapter
import com.zhusx.core.app._BaseFragment
import com.zhusx.core.imp.SimpleRecyclerAdapter
import com.zhusx.core.interfaces.IHttpResult
import com.zhusx.core.network.HttpRequest
import echat.future.cn.echat.R
import echat.future.cn.echat.home.bean.BannerEntity
import echat.future.cn.echat.home.bean.HomeEntity
import echat.future.cn.echat.home.network.LoadData
import echat.future.cn.echat.home.network.SimpleHttpListener
import echat.future.cn.echat.message.weekrank.RankListActivity
import echat.future.cn.echat.my.view.WebViewActivity
import kotlinx.android.synthetic.main.fragment_home_item.*

/**
 *
 * Author  zhusx
 * Email   327270607@qq.com
 * Create  2018/8/20 20:25
 */
class HomeItemFragment : _BaseFragment() {
    private lateinit var adapter: SimpleRecyclerAdapter<HomeEntity>
    private lateinit var HFAdapter: _HFRecyclerAdapter
    var index = 0
    private var type = ""
    private var empty = -1
    private val sex = arrayOf("男", "女")
    private val gj = arrayOf("yg", "jg", "cg")
    private var gl = ""
    private val bannerData by lazy {
        LoadData<List<BannerEntity>>(LoadData.Api.banner, this)
                .apply {
                    _setOnLoadingListener(object : SimpleHttpListener<List<BannerEntity>>() {
                        override fun onLoadComplete(api: LoadData.Api, request: HttpRequest<Any>, result: IHttpResult<List<BannerEntity>>) {
                            if (result.data.isNotEmpty()) {
                                val view = LayoutInflater.from(activity).inflate(R.layout.pager_home_top, recyclerView, false)
                                val viewPager = view.findViewById<ViewPager>(R.id.viewPager)
                                viewPager.adapter = object : _BasePagerAdapter<BannerEntity>(result.data) {
                                    override fun getView(inflater: LayoutInflater, p1: Int, s: BannerEntity, p3: View?, p4: ViewGroup?): View {
                                        return ImageView(inflater.context).also {
                                            it.layoutParams = ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                                            it.scaleType = ImageView.ScaleType.CENTER_CROP
                                            Glide.with(this@HomeItemFragment).load(s.banner_img).into(it)
                                            it.setOnClickListener {
                                                when (s.type) {
                                                    1 -> {
                                                    }
                                                    2 -> {
                                                        startActivity(Intent(activity, RankListActivity::class.java))
                                                    }
                                                    3 -> {
                                                        startActivity(Intent(activity, WebViewActivity::class.java).putExtra("url", s.url))
//                                                        try {
//                                                            startActivity(Intent(Intent.ACTION_VIEW, Uri.parse(s.url)))
//                                                        } catch (e: Exception) {
//                                                        }
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                                view.findViewById<BezierBannerDot>(R.id.banner).attachToViewpager(viewPager)
                                HFAdapter.addHeaderView(view)
                                HFAdapter.notifyDataSetChanged()
                            }
                        }
                    })
                }
    }
    private val homeData by lazy {
        LoadData<List<HomeEntity>>(LoadData.Api.homePage, this)
                .apply {
                    _setOnLoadingListener(object : SimpleHttpListener<List<HomeEntity>>() {
                        override fun onLoadError(api: LoadData.Api, request: HttpRequest<Any>, result: IHttpResult<List<HomeEntity>>?, b: Boolean, error: String) {
                            swipeRefreshLayout.isRefreshing = false
                        }

                        override fun onLoadComplete(api: LoadData.Api, request: HttpRequest<Any>, result: IHttpResult<List<HomeEntity>>) {
                            swipeRefreshLayout.isRefreshing = false
                            empty = R.layout.layout_empty
                            if (request.isRefresh) {
                                adapter._setItemToUpdate(result.data)
                            } else {
                                adapter._addItemToUpdate(result.data)
                            }
                        }
                    })
                }
    }

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.fragment_home_item, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initView()
    }

    private fun initView() {
        adapter = object : SimpleRecyclerAdapter<HomeEntity>(R.layout.list_item_home) {
            override fun __getEmptyLayoutResource() = empty

            override fun bindViewHolder(holder: _ViewHolder, position: Int, s: HomeEntity) {
                holder.setText(R.id.tv_price, "${s.price}币/分钟")
                holder.setText(R.id.tv_name, s.username)
                holder.setText(R.id.tv_message, s.sign)
                when (s.anchor_status ?: "") {
                    "0" -> {
                        holder.setImageRes(R.id.iv_status, R.drawable.btn_lixian)
                    }
                    "1" -> {
                        holder.setImageRes(R.id.iv_status, R.drawable.btn_zaixian)
                    }
                    "2" -> {
                        holder.setImageRes(R.id.iv_status, R.drawable.btn_zailiao)
                    }
                    else -> {
                        holder.setImageRes(R.id.iv_status, R.drawable.btn_lixian)
                    }
                }
                when (s.gj ?: "${gl}") {
                    "yg" -> {
                        holder.setImageRes(R.id.iv_gj, R.drawable.btn_guan_yin)
                    }
                    "jg" -> {
                        holder.setImageRes(R.id.iv_gj, R.drawable.btn_guan_huang)
                    }
                    "cg" -> {
                        holder.setImageRes(R.id.iv_gj, R.drawable.btn_guan_cai)
                    }
                    else -> {
                        holder.setImageRes(R.id.iv_gj, R.drawable.btn_guan_yin)
                    }
                }
                when (s.user_role) {
                    3 -> {
                        holder.getView<View>(R.id.iv_v).visibility = View.VISIBLE
                    }
                    else -> {
                        holder.getView<View>(R.id.iv_v).visibility = View.GONE
                    }
                }
                Glide.with(this@HomeItemFragment).load(s.avatar).into(holder.getView(R.id.iv_image))
                holder.rootView.setOnClickListener { startActivity(Intent(activity, AnchorHomeActivity::class.java).putExtra(_EXTRA_String_ID, "${s.id}")) }
                if (position == itemCount - 1) {
                    if (homeData.hasMoreData()) {
                        homeData._reLoadData(false)
                    }
                }
            }
        }
        if (index == 0) {
            HFAdapter = _HFRecyclerAdapter(adapter)
            recyclerView.adapter = HFAdapter
        } else if (index == 2) {
            HFAdapter = _HFRecyclerAdapter(adapter)
            HFAdapter.addFooterView(LayoutInflater.from(activity).inflate(R.layout.layout_footer, recyclerView, false))
            recyclerView.adapter = HFAdapter
        } else {
            recyclerView.adapter = adapter
        }
        when (index) {
            0 -> {
                bannerData._loadData()
                type = ""
            }
            1 -> {
                type = "new"
            }
            2 -> {
                type = "focus"
            }
            3 -> {
                type = "star"
                gl = "yg"
            }
            4 -> {
                type = "star"
                gl = "jq"
            }
            5 -> {
                type = "star"
                gl = "cg"
            }
        }
        refresh(0)
        swipeRefreshLayout.setOnRefreshListener {
            if (homeData._isLoading()) {
                swipeRefreshLayout.isRefreshing = false
            }
            homeData._refreshData(type, gl)
        }
//        appBarLayout.addOnOffsetChangedListener { appBarLayout, verticalOffset ->
//            swipeRefreshLayout.isEnabled = verticalOffset >= 0
//        }
    }

    fun refresh(choose: Int) {
        when (index) {
            2 -> {
                gl = gj[choose]
            }
//            4 -> {
//                gl = sex[choose]
//            }
        }
        swipeRefreshLayout.isRefreshing = true
        homeData._refreshData(type, gl)
    }
}